package com.example.demo.domain.category;

import com.example.demo.domain.category.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 应用分类的排序服务
 *
 * @author yingjianhua
 */
@Service
public class CategorySortService {

    @Autowired
    private CategoryRepository repository;

    public int generateSort() {
        return (int)repository.count();
    }

    public void sortByName(Set<String> names) throws Exception {
        final List<Category> list = repository.findAll();
        if (names.size() != list.size()) {
            // 首先需要确保names的正确，必须和数据库中的一一对应
            // 通过两步进行确认， 1. 数据数量和数据库中的一致， 2. 每个名字都能在数据库中找到对应的数据
            throw new Exception("数据异常");
        }
        final Map<String, Category> nameCategoryMap = list.stream().collect(Collectors.toMap(Category::getName, x -> x));
        int sort = 0;
        for (String name : names) {
            final Category category = nameCategoryMap.get(name);
            if (category == null) {
                // 前端数据正确性判断
                throw new Exception("数据异常");
            }
            if (!category.getSort().equals(sort)) {
                changeSort(category, sort);
            }
            sort ++;
        }
    }

    private void changeSort(Category category, Integer sort) throws IllegalAccessException, NoSuchFieldException {
        Field sortField = Category.class.getDeclaredField("sort");
        ReflectionUtils.makeAccessible(sortField);
        sortField.set(category, sort);
        repository.save(category);
    }
}
